package com.dtlaya.allutils.fileTranction;

import com.dtlaya.allutils.dcmFileUpload.config.DicomStorageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FileStorageService {

    private final Path fileStorageLocation;

    @Autowired
    public FileStorageService(DicomStorageProperties fileStorageProperties) {
        this.fileStorageLocation = Paths.get(fileStorageProperties.getBasePath())
                                      .toAbsolutePath().normalize();
        try {
            try {
                Files.createDirectories(this.fileStorageLocation);
            } catch (Exception ex) {
                throw new RuntimeException("无法创建文件存储目录", ex);
            }
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据SeriesId加载文件
     * @param seriesId 系列ID
     * @return 文件资源
     */
    public Resource loadFileBySeriesId(String seriesId) {
        try {
            // 在实际应用中，这里应该查询数据库获取文件路径
            // 这里简化为直接在存储位置查找
            Path filePath = this.fileStorageLocation.resolve(seriesId).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists()) {
                return resource;
            } else {
                throw new RuntimeException("文件未找到: " + seriesId);
            }
        } catch (MalformedURLException ex) {
            throw new RuntimeException("文件读取错误: " + seriesId, ex);
        }
    }

    /**
     * 获取Series下的所有文件
     * @param seriesId 系列ID
     * @return 文件列表
     */
    public List<String> listFilesBySeriesId(String seriesId) {
        try {
            // 在实际应用中，这里应该查询数据库获取文件列表
            // 这里简化为直接在存储位置查找
            Path seriesPath = this.fileStorageLocation.resolve(seriesId);
            
            return Files.walk(seriesPath, 1)
                      .filter(path -> !path.equals(seriesPath))
                      .map(path -> path.getFileName().toString())
                      .collect(Collectors.toList());
        } catch (IOException ex) {
            throw new RuntimeException("无法列出文件: " + seriesId, ex);
        }
    }
}